import 'package:flutter_bilibili/http/adapter/dio_adapter.dart';
import 'package:flutter_bilibili/http/adapter/hi_net_adapter.dart';
import 'package:flutter_bilibili/http/request/base_request.dart';

import 'hi_error.dart';

class HiNet {
  static HiNet? _instance;

  // 工厂函数返回单例
  factory HiNet() {
    _instance ??= HiNet._internal();
    return _instance!;
  }

  HiNet._internal();

  /// 发送请求
  Future<dynamic> send<T>(BaseRequest request) async {
    printLog('url:${request.url()}');

    HiNetAdaptor adaptor = DioAdapter();
    return adaptor.send(request);
  }

  Future fire(BaseRequest request) async {
    HiNetResponse response;

    try {
      response = await send(request);
      var code = response.statusCode;
      var result = response.data;
      switch (code) {
        case 200:
          return result;
        case 401:
          throw NeedLogin();
        case 403:
          throw NeedAuth(result.toString(), data: result);
        default:
          throw HiNetError(code, result.toString(), data: result);
      }
    } on HiNetError catch (e) {
      printLog(e);
    } catch (e) {
      // 其他异常
      printLog(e);
    }
  }

  void printLog(log) {
    print('hi_net:${log.toString()}');
  }
}
